<?php

namespace App\Service\UserService;

use App\Model\PssModel\PddToken;
use App\Model\PssModel\YouzanGoods;
use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Service\VendorClient\ShopYouZanApi\ShopYouZanApiClient;
use Hyperf\Utils\WaitGroup;

class YouzanService extends BaseService
{
    /**
     * 接收消息数据
     * @param string $messageType
     * @param array $data
     */
    public function MessageRev(string $messageType, array $goodsList, array $binfo)
    {
        $shopInfoObJ = PddToken::instance()->where('status', 1)->where('auth_type', PddToken::AUTH_TYPE_YOUZ)
            ->where('bid', $binfo['bid'])->first();

        if (empty($shopInfoObJ)) {
            return Normal::returnCode(Normal::FAIL, '未找到店铺信息');
        }

        $shopInfo = $shopInfoObJ->toArray();

        //判断是否支持处理商品
        $extends = json_decode($shopInfo['extends'], true);
        if (isset($extends['is_not_support_good'])) {
            return Normal::returnCode(Normal::SUC, '无需处理');
        }
        $is_chain_store = false;
        $mall_id = $shopInfo['mall_id'];
        if (isset($extends['is_chain_store'])) {
            $mall_id = $extends['chain_store_parent_id'] ?? $shopInfo['mall_id'];
            $is_chain_store = true;
        }

        if ($messageType == 'goodsSkuChange') {

            if ($is_chain_store) {
                //如果是连锁店无法下架商品,只能将库存置为0
                return $this->goodsSkuChangeByChainStore($goodsList['skuList'], $mall_id);
            }
            return $this->goodsSkuChange($goodsList['skuList'], $mall_id);
        }

        if ($messageType == 'goodsBatchDown') {
            if ($is_chain_store) {
                //如果是连锁店无法下架商品,只能将库存置为0
                return $this->goodsBatchDownByChainStore($goodsList['skuList'], $mall_id);
            }
            return $this->goodsBatchDown($mall_id);
        }

        if ($messageType == 'goodsChange') {
            return $this->goodsChange($goodsList, $mall_id);
        }

        return Normal::returnCode(Normal::FAIL, '不支持的方法');
    }



    /**
     * 商品下架
     * @param [type] $skuCodes
     * @param [type] $kdtId
     * @return void
     */
    private function goodsSkuChange($skuCodes, $kdtId)
    {
        //处理下架
        $goodsIdListData = YouzanGoods::instance()
            ->whereIn('skucode', $skuCodes)
            ->select(['goods_id', 'kdt_id'])
            ->where('kdt_id', $kdtId)
            ->get()
            ->toArray();
        if (empty($goodsIdListData)) {
            return Normal::returnCode(Normal::FAIL, '无匹配的有赞商品idList');
        }
        $goodsIdsTotalList = array_chunk($goodsIdListData, 50);

        //50个一组调用协程
        foreach ($goodsIdsTotalList as $goodsIdList) {
            $count = count($goodsIdList);
            $wg = new WaitGroup();
            $wg->add($count);
            $result_update = [];
            foreach ($goodsIdList as $goods) {
                co(function () use ($wg, $goods, &$result_update) {
                    $response = ShopYouZanApiClient::instance()->updateGoodsDown($goods['goods_id'], $goods['kdt_id']);
                    $result_update[] = $response;
                    $wg->done();
                });
            }
            $wg->wait();
        }
        return Normal::returnCode(Normal::SUC, '处理完成');
    }

    /**
     * 商品下架(连锁店)
     * @param [type] $skuCodes
     * @param [type] $kdtId
     * @return void
     */
    private function goodsSkuChangeByChainStore($skuCodes, $kdtId)
    {
        //处理下架
        $goodsIdListData = YouzanGoods::instance()
            ->whereIn('skucode', $skuCodes)
            ->select(['goods_id', 'kdt_id'])
            ->where('kdt_id', $kdtId)
            ->get()
            ->toArray();
        if (empty($goodsIdListData)) {
            return Normal::returnCode(Normal::FAIL, '无匹配的有赞商品idList');
        }
        $goodsIdsTotalList = array_chunk($goodsIdListData, 50);

        //50个一组调用协程
        foreach ($goodsIdsTotalList as $goodsIdList) {
            $count = count($goodsIdList);
            $wg = new WaitGroup();
            $wg->add($count);
            $result_update = [];
            foreach ($goodsIdList as $goods) {
                co(function () use ($wg, $goods, &$result_update) {
                    $response = ShopYouZanApiClient::instance()->editNormalGoods([
                        'item_id' => $goods['goods_id'],
                        'quantity' => 0
                    ], $goods['kdt_id']);
                    $result_update[] = $response;
                    $wg->done();
                });
            }
            $wg->wait();
        }
        return Normal::returnCode(Normal::SUC, '处理完成');
    }


    public function goodsBatchDown($kdtId)
    {
        //处理下架
        $goodsIdListData = YouzanGoods::instance()
            ->select(['goods_id', 'kdt_id'])
            ->where('kdt_id', $kdtId)
            ->get()
            ->toArray();
        if (empty($goodsIdListData)) {
            return Normal::returnCode(Normal::FAIL, '无匹配的有赞商品idList');
        }
        $goodsIdsTotalList = array_chunk($goodsIdListData, 50);

        //50个一组调用协程
        foreach ($goodsIdsTotalList as $goodsIdList) {
            $count = count($goodsIdList);
            $wg = new WaitGroup();
            $wg->add($count);
            $result_update = [];
            foreach ($goodsIdList as $goods) {
                co(function () use ($wg, $goods, &$result_update) {
                    $response = ShopYouZanApiClient::instance()->updateGoodsDown($goods['goods_id'], $goods['kdt_id']);
                    $result_update[] = $response;
                    $wg->done();
                });
            }
            $wg->wait();
        }
        return Normal::returnCode(Normal::SUC, '处理完成');
    }


    public function goodsBatchDownByChainStore($kdtId)
    {
        //处理下架
        $goodsIdListData = YouzanGoods::instance()
            ->select(['goods_id', 'kdt_id'])
            ->where('kdt_id', $kdtId)
            ->get()
            ->toArray();
        if (empty($goodsIdListData)) {
            return Normal::returnCode(Normal::FAIL, '无匹配的有赞商品idList');
        }
        $goodsIdsTotalList = array_chunk($goodsIdListData, 50);

        //50个一组调用协程
        foreach ($goodsIdsTotalList as $goodsIdList) {
            $count = count($goodsIdList);
            $wg = new WaitGroup();
            $wg->add($count);
            $result_update = [];
            foreach ($goodsIdList as $goods) {
                co(function () use ($wg, $goods, &$result_update) {
                    $response = ShopYouZanApiClient::instance()->editNormalGoods([
                        'item_id' => $goods['goods_id'],
                        'quantity' => 0
                    ], $goods['kdt_id']);
                    $result_update[] = $response;
                    $wg->done();
                });
            }
            $wg->wait();
        }
        return Normal::returnCode(Normal::SUC, '处理完成');
    }


    /**
     * 商品新增或修改
     * @param [type] $skuCodes
     * @param [type] $kdtId
     * @return void
     */
    private function goodsChange($goodsList, $kdt_id)
    {
        //查询数据
        $goodsChangeList = [];
        foreach ($goodsList as $goodsItem) {
            $skuList = current($goodsItem['skuList']);
            $storeList = current($skuList['storeList']);
            $batchInfo = current($storeList['goods_batch_list']);
            $specInfo = current($batchInfo['spec_list']);
            $skuCode = $batchInfo['supplier_skucode'];
            //拼装商品数组
            $goodsChangeList[$skuCode] = [
                'skucode' => $skuCode,
                'quantity' => $batchInfo['num'],
                'price' => $specInfo['price'],
                'origin_price' => $specInfo['priceMarket'],
                'desc' => $goodsItem['description'],
                'title' => $goodsItem['goodsName'],
                'tax_rate' => $skuList['tax_rate'],
                'has_rate' => $skuList['has_rate'],
                'costPrice' => $specInfo['priceSettlement'],
                'goods_type' => $goodsItem['goodsType'],
                'images' => $goodsItem['images'],
            ];
        }
        $skuCodeArr = array_keys($goodsChangeList);
        $authSkuGoods = YouzanGoods::instance()->whereIn('skucode', $skuCodeArr)->where('kdt_id', $kdt_id)->get()->toArray();

        //这里需要判断是否已存在数据
        $youzanGoodsMap = array_column($authSkuGoods, NULL, 'skucode');
        $youzanIsExistGoodsSkuCode = array_keys($youzanGoodsMap);
        $insertMysqlDatas = [];

        $count = count($goodsChangeList);
        $wg = new WaitGroup();
        $wg->add($count);


        //判断是否已经存在有赞平台
        foreach ($goodsChangeList as $goodsChange) {

            co(function () use ($wg, $goodsChange, $youzanIsExistGoodsSkuCode, $youzanGoodsMap, $kdt_id, &$insertMysqlDatas) {
                if (in_array($goodsChange['skucode'], $youzanIsExistGoodsSkuCode)) {
                    //修改商品
                    $this->editGoods($goodsChange, $youzanGoodsMap[$goodsChange['skucode']], $kdt_id);
                } else {
                    //新增商品
                    $insertResult = $this->insertGoods($goodsChange, $kdt_id);
                    if ($insertResult['code'] == Normal::SUC) {
                        $insertMysqlDatas[] = $insertResult['data'];
                    }
                }
                // $result_update[] = $response;
                $wg->done();
            });
        }
        $wg->wait();
        //判断是否有需要添加的数据
        if (!empty($insertMysqlDatas)) {
            YouzanGoods::instance()->insert($insertMysqlDatas);
        }

        return Normal::returnCode(Normal::SUC, '处理完成');
    }


    /**
     * 新增商品
     * @param [type] $goodsInfo
     * @param [type] $youzanGoodsInfo
     * @return void
     */
    private function insertGoods($goodsInfo, $kdt_id)
    {
        //可能需要先上传图片,调用到有赞的上传图片接口这里并发去处理
        //整理出需要上传的图片
        $imgRes = $this->updateImgs($goodsInfo['images'], $kdt_id);
        //判断商品类型 
        if ($goodsInfo['goods_type'] == 0) {
            //一般贸易商品 直接调用新增商品接口
            $result = ShopYouZanApiClient::instance()->insertNormalGoods([
                'desc' => $goodsInfo['desc'],
                'item_price_param' => [
//                    'origin'     => $goodsInfo['origin_price'],
                    'cost_price' => $this->multiplyByOneHundred($goodsInfo['costPrice']),
                    'price'      => $this->multiplyByOneHundred($goodsInfo['price']),
                ],
                'title' => $goodsInfo['title'],
                'quantity' => $goodsInfo['quantity'],
                'image_ids' => $imgRes,
                'item_no'  => $goodsInfo['skucode']
            ], $kdt_id);
        } else {
            //保税和直邮商品 这里就需要调用海淘商品的接口
            $result = ShopYouZanApiClient::instance()->insertHaiTaoGoods([
                'desc'       => $goodsInfo['desc'],
                'cost_price' => $this->multiplyByOneHundred($goodsInfo['costPrice']),
                'price'      => $this->multiplyByOneHundred($goodsInfo['price']),
                'title'      => $goodsInfo['title'],
                'quantity'   => $goodsInfo['quantity'],
                'goods_type' => $goodsInfo['goods_type'],
                'tax_rate'   => $goodsInfo['tax_rate'],
                'has_rate'      => $goodsInfo['has_rate'],
                'origin_price'   => $goodsInfo['origin_price'],
                'images'      => implode(',', $imgRes),
                'item_no'     => $goodsInfo['skucode']
            ], $kdt_id);
        }
        if ($result['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::FAIL, $result['message'] ?? '新增商品失败', []);
        }
        return Normal::returnCode(Normal::SUC, '新增商品成功', [
            'goods_id' => $result['data']['item_id'] ?? $result['data']['item']['itemId'],
            'skucode'  => $goodsInfo['skucode'],
            'kdt_id'   => $kdt_id,
            'images'   => implode(',', $imgRes),
            'cd'       => time(),
            'md'       => time()
        ]);
    }

    private function updateImgs($images, $kdt_id)
    {
        $imagesList = array_chunk($images,3);
        $result_update = [];
        foreach ($imagesList as $newImgList) 
        {
            $count = count($newImgList);
            $wg = new WaitGroup();
            $wg->add($count);
            foreach ($newImgList as $image) 
            {
                co(function () use ($wg, $image, $kdt_id, &$result_update) 
                {
                    $response = $this->uploadImageSource($image, $kdt_id);
                    $result_update[] = $response;
                    $wg->done();
                });
            }
            $wg->wait();
        }
        $reutrnImgIds = [];
        foreach ($result_update as $result) {
            if ($result['code'] == Normal::SUC) {
                $reutrnImgIds[] = $result['data']['image_id'];
            }
        }
        return $reutrnImgIds;
    }

    private function uploadImageSource($image_path, $kdt_id)
    {
        try {
            $filename = __DIR__ . '/' . date("YmdHis") . '_' . rand() . '_' . uniqid('youzan') . '.jpg';
            //读取图片资源
            $image_soure = file_get_contents($image_path);
            //写入本地指定路径(用完之后删除)
            chmod(__DIR__, 777);
            file_put_contents($filename, $image_soure);
            $result  = ShopYouZanApiClient::instance()->uploadImageCurl([
                'storeID' => $kdt_id,
                'images'  => $filename
            ]);

            //token获取出来的地址
            unlink($filename);
            if (isset($result["code"]) && $result["code"] == Normal::SUC) {
                return Normal::returnCode(Normal::SUC, "图片上传成功", $result['data']);
            }
            return Normal::returnCode(Normal::FAIL, "图片上传失败" . $result["retmsg"], $result);
        } catch (\Exception $th) {
            return Normal::returnCode(Normal::FAIL, "图片上传操作失败【{$th->getMessage()}{$th->getLine()}{$th->getFile()}】");
        }
    }

    private function editGoods($goodsInfo, $youzanGoodsInfo, $kdt_id)
    {
        //判断商品类型 
        if ($goodsInfo['goods_type'] == 0) {
            //一般贸易商品 直接调用新增商品接口
            $result = ShopYouZanApiClient::instance()->editNormalGoods([
                'item_id' => $youzanGoodsInfo['goods_id'],
                'desc' => $goodsInfo['desc'],
                // 'item_price_param' => [
                //     'origin'     => $goodsInfo['origin_price'],
                //     'cost_price' => $this->multiplyByOneHundred($goodsInfo['costPrice']),
                //     'price'      => $this->multiplyByOneHundred($goodsInfo['price']),
                // ],
                'title' => $goodsInfo['title'],
                'quantity' => $goodsInfo['quantity']
            ], $kdt_id);
        } else {
            //保税和直邮商品 这里就需要调用海淘商品的接口
            $result = ShopYouZanApiClient::instance()->editHaiTaoGoods([
                'item_id' => $youzanGoodsInfo['goods_id'],
                'desc'       => $goodsInfo['desc'],
                'cost_price' => $this->multiplyByOneHundred($goodsInfo['costPrice']),
                'price'      => $this->multiplyByOneHundred($goodsInfo['price']),
                'title'      => $goodsInfo['title'],
                'quantity'   => $goodsInfo['quantity'],
                'goods_type' => $goodsInfo['goods_type'],
                'tax_rate'   => $goodsInfo['tax_rate'],
                'has_rate'   => $goodsInfo['has_rate'],
                'origin_price'   => $goodsInfo['origin_price'],
            ], $kdt_id);
        }

        if ($result['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::FAIL, $result['message'] ?? '新增商品失败', []);
        }
        return Normal::returnCode(Normal::SUC, '新增商品成功', [
            'goods_id' => $result['data']['item_id'],
            'skucode'  => $goodsInfo['skucode'],
            'kdt_id'   => $kdt_id
        ]);
    }

    /**
     * 价格 元转为分
     * @return string
     */
    private function multiplyByOneHundred($price, $multiple = 100, $point = 0)
    {
        return bcmul($price, $multiple);
    }

    public function orderAfterSale($params)
    {
        return Normal::returnCode(Normal::SUC, '售后成功');
    }
}
